<?php
require_once dirname(__FILE__) . '/../base/BaseDao.php';
require_once dirname(__FILE__) . '/UserConstant.php';
/**
 * Created on 2010-09-18
 * @desc		user database dao
 * @author 		micah <micah.shi@gmail.com>
 * @package 	protected.src.user.dao
 */
class UserDao extends BaseDao{
	private $tablename = UserConstant::USER_TABLE_NAME;

	/**
	 * @desc 添加用户
	 *
	 * @param array $user
	 * @return array 用户信息，失败则返回空
	 */
	public function addUser(Array $user) {
		$sql = 'INSERT INTO ' . $this->getTableName() . $this->getInsertClause($user);
		$conn = $this->getConnection();
		$stmt = $conn->prepare($sql);
		$this->bindValues($stmt, $user);
		$stmt->execute();
		return $this->findUserByName($user[UserConstant::USER_TABLE_COLUMN_USERNAME]);
	}

	/**
	 * @desc 查找用户(by $userId)
	 *
	 * @param array $userId
	 * @return array 用户信息，失败则返回空
	 */
	public function findUserById($userId) {
		$sql = "SELECT * FROM {$this->getTableName()} WHERE userid= :userid limit 1 ";
		$stmt = $this->getConnection()->prepare($sql);
		$stmt->bindValue(':userid' , $userId);
		$stmt->execute();
		$rows = $stmt->fetch(PDO::FETCH_ASSOC);
		return $rows ? $rows : null;
	}

	/**
	 * @desc 查找用户(by $userName)
	 *
	 * @param array $userName
	 * @return array 用户信息，失败则返回空
	 */
	public function findUserByName($userName) {
		$sql = "SELECT * FROM {$this->getTableName()} WHERE username = :username limit 1 ";
		$stmt = $this->getConnection()->prepare($sql);
		$stmt->bindValue(':username' , $userName);
		$stmt->execute();
		$rows = $stmt->fetch(PDO::FETCH_ASSOC);
		return $rows ? $rows : null;
	}

	/**
	 * @desc 用户名密码验证
	 *
	 * @param array $userName,$password
	 * @return Boolen true or false
	 */
	public function checkUserNameAndPassword($userName,$password) {
		$sql = "SELECT * FROM {$this->getTableName()} WHERE username = :username and password = :password";
		$stmt = $this->getConnection()->prepare($sql);
		$stmt->bindValue(':username' , $userName);
		$stmt->bindValue(':password' , $password);
		$stmt->execute();
		$rows = $stmt->fetch(PDO::FETCH_ASSOC);
		return $rows ? $rows : null;
	}

	public function getConnection() {
		require_once dirname(__FILE__) . '/../ConnectionFactory.php';
		return ConnectionFactory::getInstance ()->getConnection ();
	}

	public function getTableName(){
		return $this->tablename;
	}
}
?>